<template>
    <div class="upload-box">

        <div class="upload flex-center-col" @click="clickUpload">
             <span style="font-size:50px;color:black">
                    +
            </span>
        </div>
        <div class="showImage">
            <img :src="obj.imageSrc" alt="暂无图片" v-show="obj.imageSrc!= ''">
        </div>


        <input type="file"
               @change="fileChange"
               ref="image"
               name="file"
               accept="image/*"
               style="display: none"
        >
    </div>
</template>

<script>
    import {reactive, ref} from "@vue/reactivity";

    export default {
        name: "Upload",
        props:{
            max:{
                type:Number,
                default:1
            }
        },
        setup(props,ctx){

            let obj=reactive({
                imageSrc:""
            })
            let image=ref()

            function  fileChange(e) {


                let fileList=e.target.files

                // 交出事件
                ctx.emit('file',fileList[0])
                // 显示预览图
                showBaseImage(fileList)
            }
            function  showBaseImage(fileList) {
                let fileReader = new FileReader();
                fileReader.readAsDataURL(fileList[0])
                fileReader.onload=function (e) {
                    // 回填图片（预览图片）
                    obj.imageSrc=e.target.result
                }

            }
            function  clickUpload() {
                image.value.click()
            }

            return {
                image,
                fileChange,
                clickUpload,
                obj
            }
        }
    }
</script>

<style scoped lang="less">

    .upload-box{
        width: 100%;
        height: 100%;
        min-width: 350px;
        min-height: 100px;
        max-height: 200px;

        display: flex;
        align-items: center;
        .upload{
            width: 200px;
            height: 100%;
            min-height: 100px;
            cursor: pointer;
            background-color: #eeebeb;
            margin-right: 50px;
            border: 1px solid gray;
        }
        .upload:hover{
            background-color: #42b983;
        }
        .showImage{
            width: 100px;
            height: 100px;
            min-height: 100px;
            overflow: hidden;
            img{
                height: 100%;
                object-fit: cover;
            }

        }
    }

</style>